#include <SimpleAmqpClient/SimpleAmqpClient.h>
#include <iostream>
#include <string>

int main() {
    try {
        // 创建连接
        AmqpClient::Channel::ptr_t channel = AmqpClient::Channel::Create("localhost");
        
        // 声明一个topic类型的exchange
        std::string exchange_name = "topic_logs";
        channel->DeclareExchange(
            exchange_name,                    // exchange名称
            AmqpClient::Channel::EXCHANGE_TYPE_TOPIC, // exchange类型
            false,                            // durable
            false,                            // autodelete
            false                             // passive
        );
        
        // 声明一个唯一的队列（每个消费者都有自己的队列）
        std::string queue_name = channel->DeclareQueue(
            "",           // 空字符串表示让服务器生成唯一队列名
            false,        // passive
            false,        // durable
            false,         // exclusive - 排他队列，连接断开时自动删除
            true          // auto_delete - 不使用时自动删除
        );
        
        // 绑定队列到exchange，使用绑定键
        std::string binding_key = "*.info"; // 示例：接收所有info级别的消息
        channel->BindQueue(queue_name, exchange_name, binding_key);
        
        // 设置消费者
        std::string consumer_tag = channel->BasicConsume(
            queue_name,   // 队列名称
            "",           // 消费者标签
            true,         // no_local
            false,        // no_ack - 手动确认消息
            false,        // exclusive
            10            // 消息预取数量
        );
        
        std::cout << "Waiting for messages with binding key '" << binding_key 
                  << "'. To exit press CTRL+C" << std::endl;
        
        while (true) {
            // 获取消息
            AmqpClient::Envelope::ptr_t envelope = channel->BasicConsumeMessage(consumer_tag);
            
            // 处理消息
            std::string message_body = envelope->Message()->Body();
            std::string routing_key = envelope->RoutingKey();
            std::cout << " [x] Received '" << routing_key << "':'" << message_body << "'" << std::endl;
            
            // 手动确认消息
            channel->BasicAck(envelope);
        }
        
    } catch (const std::exception& ex) {
        std::cerr << "Error: " << ex.what() << std::endl;
        return 1;
    }
    
    return 0;
}